package cn.com.mayue.guava.services;

import com.github.rholder.retry.*;
import com.google.common.base.Predicates;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * Created by mayue
 * 测试guava-retrying重试机制
 * guava-retrying 官网demo
 * spring-retry差不多
 */
public class GuavaRetryingTest {
    @Test
    public void test(){
        Callable<Boolean> callable = new Callable<Boolean>() {
            public Boolean call() throws Exception {
                System.out.println("call。。。");
                //返回null触发重试
                return null;
            }
        };

        //支持Exception异常对象 和自定义断言对象
        Retryer<Boolean> retry = RetryerBuilder.<Boolean>newBuilder()
                .retryIfResult(Predicates.<Boolean>isNull())
                //IOException则重试
                .retryIfExceptionOfType(IOException.class)
                //runtimeException则重试
                .retryIfRuntimeException()
                //重试3次后结束
                .withStopStrategy(StopStrategies.stopAfterAttempt(3))
                .withWaitStrategy(WaitStrategies.fixedWait(1L, TimeUnit.SECONDS))
                .build();
        try {
            retry.call(callable);
        } catch (RetryException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
